#Anaconda/envs/pyqtenv python
# -*- coding: utf-8 -*-
'''
DevWebController.py
===================

.. module:: DevWebController
  :platform: Windows
  :synopsis: 网络浏览器控制模块，可用于网络爬虫功能，模拟浏览器操作，获取网页内容等。

.. moduleauthor:: CRC1109-WangXi

简介
----

该模块实现了网络浏览器控制模块的功能，主要用于网页自动化相关的应用程序中。它提供了以下特性：

- 使用Selenium组件实现网页浏览器的控制
- 支持基本网页自动化操作（如打开网页、输入内容、点击按钮、获取网页内容等）

版本
----

- 版本 1.0 (2025/04/27): 初始版本

'''

import os

from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from PyQt5.QtWidgets import QTextBrowser

from Netterminal.Sources.Device.DevBase import DevBase

class DevWebController(DevBase):
    def __init__(self, name:str, **kwargs):
        super(DevWebController,self).__init__(name)
        
        self.register(**kwargs)

    def register(self, **kwargs):
        self.tb_showinfo:QTextBrowser = kwargs.get('tb_showinfo')
        
    def ready(self):
        service = EdgeService(executable_path=self._get_webdriver_path())
        edge_options = webdriver.EdgeOptions()
        edge_options.add_argument("--headless")  # 启用无头模式

        self.driver = webdriver.Edge(service=service, options=edge_options)

    def start(self, search_text:str):
        self.driver.get("https://cn.bing.com/")

        search_box = self.driver.find_element(By.ID, "sb_form_q")
        search_box.send_keys(search_text)
        search_box.send_keys(Keys.RETURN)

        try:
            WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CLASS_NAME, "b_algo"))
            )
        except:
            self.tb_showinfo.append("搜索结果加载超时")
            return
        
        self.tb_showinfo.append("搜索结果：")
        self.tb_showinfo.append("========================================")

        # 遍历所有搜索结果
        for result in self.driver.find_elements(By.CLASS_NAME, "b_algo"):
            try:
                # 定位到 <h2> 标签
                h2_element = result.find_element(By.TAG_NAME, "h2")
                
                # 等待 <h2> 下的 <a> 标签可访问，并且其文本内容不为空
                a_element = h2_element.find_element(By.TAG_NAME, "a")
                
                # 提取 <a> 标签的文本内容（标题）
                title_text = a_element.text
                
                # 提取 <a> 标签的 href 属性（链接）
                link_url = a_element.get_attribute("href")
                
                # 打印或存储结果
                self.tb_showinfo.append(f"标题: {title_text}")
                self.tb_showinfo.append(f"链接: {link_url}")
                self.tb_showinfo.append("")
                
            except Exception as e:
                print(f"未找到标题或链接: {e}")
            
        # 关闭浏览器
        # self.driver.quit()

    def _get_webdriver_path(self):
        current_dir_path = os.path.dirname(os.path.abspath(__file__))
        webdriver_path = os.path.join(current_dir_path, "msedgedriver.exe")
        if not os.path.exists(webdriver_path):
            raise FileNotFoundError("msedgedriver.exe not found in current directory.")
        return webdriver_path
    